package com.zly.app.controller;

import com.github.pagehelper.PageInfo;
import com.zly.app.dto.AppInfoDto;
import com.zly.app.entity.AppInfo;
import com.zly.app.entity.DevUser;
import com.zly.app.service.AppCategoryService;
import com.zly.app.service.AppInfoService;
import com.zly.app.util.SessionUtil;
import com.zly.app.util.SysConStatus;
import com.zly.app.vo.CategoryTreeVo;
import com.zly.app.vo.ResultVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/appInfo")
public class AppInfoController {

    @Autowired
    AppInfoService appInfoService;

    @Autowired
    AppCategoryService appCategoryService;


    @PostMapping("/tree")
    public ResultVo tree(){
        try {
            CategoryTreeVo vo = appCategoryService.tree();
            return ResultVo.success("",vo);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVo.error("");
        }

    }

    @PostMapping("/pageList")
    public ResultVo getPage(@RequestBody AppInfoDto appInfoDto,@RequestParam(defaultValue = "1")Integer pageNum,HttpServletRequest request){
        String toKen = request.getHeader("toKen");
        String[] split = toKen.split("-");
        String type = split[3];
        if (type.equals(SysConStatus.UserTypeStr.admin)){
            appInfoDto.setStatus(1L);
            try{
                PageInfo<AppInfo> page = appInfoService.getPage(appInfoDto,pageNum);
                return ResultVo.success(null,page);
            }catch(Exception e){
                e.printStackTrace();
                return ResultVo.error(null);
            }

        }else if(type.equals(SysConStatus.UserTypeStr.dev)){
            String devid = split[2];
            appInfoDto.setDevid(Long.valueOf(devid));
            try{
                PageInfo<AppInfo> page = appInfoService.getPage(appInfoDto,pageNum);
                return ResultVo.success(null,page);
            }catch(Exception e){
                e.printStackTrace();
                return ResultVo.error(null);
            }
        }else {
            throw new RuntimeException("非法用户");
        }
    }

    @PostMapping("/saveAndUp")
    public ResultVo saveAndUp(
            AppInfo appinfo, MultipartFile logoPic, HttpServletRequest request){
        String toKen = request.getHeader("toKen");
        if (logoPic!=null){
            if (!logoPic.isEmpty()){
                String originalFilename = logoPic.getOriginalFilename();
                String extension = FilenameUtils.getExtension(originalFilename);
                if (logoPic.getSize()>500*1024){
                    return ResultVo.error("文件大小超过500k");
                }else if (extension.equalsIgnoreCase("jpg")
                        ||extension.equalsIgnoreCase("jpeg")
                        ||extension.equalsIgnoreCase("png")
                        ||extension.equalsIgnoreCase("gif")){
                    String realPath = request.getServletContext().getRealPath("/upload/logo/");
                    File file = new File(realPath);
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    String filename = UUID.randomUUID().toString().replace("-","")+"."+extension;
                    File saveFile = new File(realPath+filename);
                    try {
                        logoPic.transferTo(saveFile);
                        appinfo.setLogopicpath("/upload/logo/"+filename);
                    }catch (IOException e){
                        e.printStackTrace();
                        return ResultVo.error("logo图片上传失败");
                    }
                }else {
                    return ResultVo.error("文件格式不正确");
                }
            }
        }
        DevUser devUser = (DevUser) SessionUtil.get(toKen);
        if (appinfo.getId()==0){
            appinfo.setStatus(1L);
            appinfo.setDevid(devUser.getId());
            appinfo.setCreatedby(devUser.getId());
            appinfo.setCreationdate(new Date());
            appinfo.setDownloads(0L);
        }else {
            appinfo.setStatus(1L);
            appinfo.setModifyby(devUser.getId());
            appinfo.setModifydate(new Date());
        }
        try {
            appInfoService.saveAndUp(appinfo);
            return ResultVo.success("",null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVo.error("");
        }

    }

    @PostMapping("/vailApk/{appid}/{apkname}")
    public ResultVo vailApk(@PathVariable Long appid,@PathVariable String apkname) {
        try {
            if (appInfoService.vailApk(appid, apkname)) {
                return ResultVo.success("apk名称可以使用", null);
            } else {
                return ResultVo.error("");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("");
        }
    }

    @PostMapping("/selApp/{appid}")
    public ResultVo selApp(@PathVariable Long appid){
        try {
           AppInfo appInfo = appInfoService.selApp(appid);
           return ResultVo.success("",appInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVo.error("");
        }
    }

    @DeleteMapping("/{appid}")
    public ResultVo delApp(@PathVariable Long appid,HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("");
        try {
            appInfoService.delApp(appid,realPath);
            return ResultVo.success("",null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVo.error("");
        }
    }

    @PutMapping("/{id}/{status}")
    public ResultVo upStatus(@PathVariable Long id,@PathVariable Long status) {
        try {
            appInfoService.upStatus(id,status);
            return ResultVo.success("",null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVo.error("");
        }
    }
}
